// pages/sign/sign.js
const app = getApp();
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    point: 0,
    continueDay: 0,
    height: wx.getSystemInfoSync().windowHeight,
    signMsg: [],
    signBtn: "签到",
    fillCard: 0,
    leakageSign: 0,
    sysW: null,
    lastDay: null,
    firstDay: null,
    year: null,
    hasEmptyGrid: false,
    cur_year: '',
    cur_month: '',
    firstDay: null,
    getDate: null,
    month: null,
    display: "none",
    signedTime:[],
    signList:[],
    signFirstTime:"",
    pixelRatio:wx.getSystemInfoSync().pixelRatio,
    // day: [{
    //   wook: '',
    //   src: "",
    // }, {
    //   wook: ''
    // }, {
    //   wook: ''
    // }, {
    //   wook: ''
    // }, {
    //   wook: ''
    // }, {
    //   wook: ''
    // }, {
    //   wook: ''
    // }],
    days:[]
    // days: [{
    //   src: "../../image/newspaper.png"
    // }]
  },
  // 签到
  sign() {
    var that=this;
    wx.request({
      url: 'https://www.xiaozheng8.com/signV2?userId=' + wx.getStorageSync("userId"),
      data: {
        "userId": wx.getStorageSync("userId")
      },
      method: 'post',
      success: function(res) {
        console.log(res);
        that.setData({
          // continueDay: res.data.data.signContinueDays,
          point:res.data.data.signPoint
        })
        that.setData({
          signBtn: "已签到"
        })
        wx.showToast({
          title: '签到成功',
        })
        that.signDetail();
        that.findSignMsg();
        that.signContinueDays();
      },
      fail: function(res) {
        wx.showToast({
          title: '签到失败',
          icon:"none"
        })
        console.log(res);
      },
      complete: function(res) {},
    })
  },
  // 问号
  questionMask() {
    wx.showToast({
      title: '完成一张订单，即可获得补签卡一张',
      icon: "none"
    })
  },
  // 签到明细
  signDetail:function(){
    var that=this;
    wx.request({
      url: 'https://www.xiaozheng8.com/signPoint?userId='+wx.getStorageSync("userId"),
      data: {
        userId: wx.getStorageSync("userId")
      },
      method: 'post',
      success: function(res) {
        console.log(res);
        that.setData({
          signMsg:res.data.data
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 查看连续签到天数
  signContinueDays(){
    var that=this;
    wx.request({
      url: 'https://www.xiaozheng8.com/continueDays?userId='+wx.getStorageSync("userId"),
      data: {
        userId: wx.getStorageSync("userId"),
      
      },
    
      method: 'post',
      success: function(res) {
        console.log(res);
        that.setData({
          continueDay:res.data.data
        })
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 补签日期
  fillDate(selectMonth){
    var that=this;
    wx.request({
      url: 'https://www.xiaozheng8.com/findSignDate',
      data: {
        userId: wx.getStorageSync("userId"),
        date: selectMonth
      },
      method: 'post',
      success: function(res) {
        console.log(res);

        var signTimeArr=res.data.data;
        var signDate=[];
        for(var i=0;i<res.data.data.length;i++){
          console.log(signTimeArr[i].signTime.split(" "));
          signDate.push(signTimeArr[i].signTime.split(" ")[0]);
        }
        that.setData({
          signList:signDate
        })
        console.log(signDate);
        var src ="../../icons/i22.png";
        for(var j=0;j<that.data.days.length;j++){
          for(var n=0;n<signDate.length;n++){
            if (that.data.days[j].day == signDate[n]){
              that.data.days[j].src=src;
              that.setData({
                days:that.data.days
              })
              console.log(that.data.days)
            }
          }
          
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 补签
  fillSign(){
    var that=this;
    wx.showModal({
      title: '提示',
      content: '消耗一张补签卡完成补签',
      success(res){
        if(res.confirm){
          that.setData({
            display:"block"
          })
          var data = new Date();
          console.log(data);
          var year = data.getFullYear();
          var month = data.getMonth() + 1;
          var fillMonth = "";
          if (month < 10) {
            fillMonth = "0" + month
          } else {
            fillMonth = month
          }
          var date = year + "-" + fillMonth
          that.fillDate(date);
        }
      }
      })
          // var myDate = new Date;
          // console.log(myDate)
          // var year = myDate.getFullYear();
          // var month = myDate.getMonth() + 1;
          // //获取当前日
          // var date = myDate.getDate();
          // var h = myDate.getHours(); //获取当前小时数(0-23)
          // var m = myDate.getMinutes(); //获取当前分钟数(0-59)
          // var s = myDate.getSeconds();
          // var timestamp = year + "-" + month + "-" + date + " " + h + ":" + m + ":" + s + "";
          // console.log(timestamp);
         
   
   
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    util.showLoading("加载中");
    var that = this;
    var height = this.data.height - 320;
    this.setData({
      height:height
    })
    console.log(res);
    var data=new Date();
    console.log(data);
    var year = data.getFullYear();
    var month = data.getMonth() + 1;
    var fillMonth="";
    if(month<10){
      fillMonth="0"+month
    }else{
      fillMonth=month
    }
    var date=year+"-"+fillMonth
    this.findSignMsg();
    this.signDetail();
    this.signContinueDays();
    this.fillDate(date);

    // 日历部分
    var that = this;
    this.setNowDate();
    this.getProWeekList()

    this.dataTime();
    var res = wx.getSystemInfoSync();
    this.setData({
      sysW: res.windowHeight / 12 - 5, //更具屏幕宽度变化自动设置宽度
      marLet: this.data.firstDay,
      getDate: this.data.getDate,
      judge: 1,
      month: this.data.month,
    });
    // util.formatTime(year);
    // wx.request({
    //   url: 'http://192.168.0.105:8002/sign?userId=' + wx.getStorageSync("userId"),
    //   data: {
    //     "userId": wx.getStorageSync("userId")
    //   },
    //   method: 'post',
    //   success: function (res) {
    //     console.log(res)
    //     if (res.data.msg=="用户已经签到了"){
    //       that.setData({
    //         signMsg:"已签到"
    //       })
    //     }
    //   },
    //   fail: function (res) {
    //     console.log(res);
    //   },
    //   complete: function (res) { },
    // })
    
  },
  // 查找
  findSignMsg(){
    var that=this;
    wx.request({
      url: 'https://www.xiaozheng8.com/signFind?userId='+wx.getStorageSync("userId"),
      data: {
        userId: wx.getStorageSync("userId")
      },
      method: 'post',
      success: function (res) {
        console.log(res);
        util.hideLoading();
        that.setData({
          point: res.data.data.signPoint,
          fillCard:res.data.data.signCard,
          leakageSign: res.data.data.signLackDays,
          signFirstTime:res.data.data.signTime
        })
        if (res.data.data.isSign == 1) {
          that.setData({
            signBtn: "已签到"
          })
        }
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) { },
    })
  },
  // 补签
  fillCheck() {
    if (this.data.leakageSign == 0) {
      wx.showToast({
        title: '您当前不需要补签',
        icon: "none"
      })
    } else if (this.data.fillCard == 0) {
      wx.showToast({
        title: '您当前没有补签卡',
        icon: "none"
      })
    }else{
      var data = new Date();
      console.log(data);
      var year = data.getFullYear();
      var month = data.getMonth() + 1;
      var fillMonth = "";
      if (month < 10) {
        fillMonth = "0" + month
      } else {
        fillMonth = month
      }
      var date = year + "-" + fillMonth
      this.fillSign(date);

    }
  },

  // 关闭日历
  onhide(){
    this.setData({
      display:"none"
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // 补签跳出日历部分函数
  getProWeekList: function () {
    let that = this
    let date = new Date()
    let dateTime = date.getTime(); // 获取现在的时间
    let dateDay = date.getDay(); // 获取现在的
    let oneDayTime = 24 * 60 * 60 * 1000; //一天的时间
    let proWeekList;
    let weekday;
    console.log(dateTime)
    for (let i = 0; i < 7; i++) {
      let time = dateTime - (dateDay - 1 - i) * oneDayTime;
      proWeekList = new Date(time).getDate(); //date格式转换为yyyy-mm-dd格式的字符串
      weekday = "day[" + i + "].wook"
      that.setData({
        [weekday]: proWeekList,
      })
      //that.data.day[i].wook = new Date(time).getDate();
    }
  },
  // 点击日期进行补签
  dateSelectAction: function (e) {
    var that=this;
    let cur_day = e.currentTarget.dataset.idx;
    let day = e.currentTarget.dataset.day;
    console.log(day.slice(0,7));
    var postDate=day.slice(0,7);
    console.log(day);
    this.setData({
      todayIndex: cur_day
    })
    var clickDay=this.data.todayIndex+1;
    console.log(this.data.todayIndex);
    // 获取到这个月第一天签到的日期
    var month=0;
    if (that.data.cur_month < 10) {
      month = "0" + that.data.cur_month
    } else {
      month = that.data.cur_month
    }
    // 第一次签到的月份
    var firstSignMonth=this.data.signFirstTime.slice(5,7);
    // 第一次签到的日期
    var firstSignDay=this.data.signFirstTime.slice(8,10);
    console.log(firstSignMonth);
    console.log(firstSignDay);
    const date = new Date();
    // 获取当前天数
    var today = date.getDate();
    console.log(today);

    // var todayDeal="";
    // if(today<10){
    //   todayDeal="0"+today
    // }else{
    //   todayDeal=today
    // }
    // 用数组存当前的月份
    var monthList=[];
    console.log(this.data.cur_month);
    var monthDeal="";
    if (this.data.cur_month < 10) {
      monthDeal = "0" + this.data.cur_month
    } else {
      monthDeal = this.data.cur_month
    }
    for(var i=0;i<that.data.signList.length;i++){
      // 首先获取到月份，如果月份相同，则可以确认本月签到情况
      monthList.push(that.data.signList[i].slice(5,7))

    }
    // 当前月份与第一次签到的月份是同一个月，第一次签到之前的日期不能签到
    var stayDay="";
    console.log(clickDay);
    // if (monthDeal == firstSignMonth){
    //   stayDay = firstSignDay.split("0");
    //   if(stayDay.length==2){
    //     if (stayDay[1] <= clickDay){

    //     } else if (stayDay[1] > clickDay){
    //       wx.showToast({
    //         title: '当前天不能补签',
    //         icon: "none"
    //       })
    //       return false;
    //     }
    //   }else if(stayDay.length==1){
    //     if(stayDay<=clickDay){

    //     }else{
    //       wx.showToast({
    //         title: '当前天不能补签',
    //         icon:"none"
    //       })
    //       return false
    //     }
    //   }
    //   if(today<=clickDay){
    //     wx.showToast({
    //       title: '当前天不能补签',
    //       icon: "none"
    //     })
    //     return false
    //   }
    // }
    // 如果签到第一次是当月的话，在判断这个月哪些天他能够补签
    // 第一天之前不能补签，当前天以后不能补签
    // debugger
    console.log(monthList);
      wx.request({
    url: 'https://www.xiaozheng8.com/replacementDate?userId=' + wx.getStorageSync("userId"),
    data: {
      userId: wx.getStorageSync("userId"),
      signTime: day
    },
    method: 'post',
    success: function (res) {
      console.log(res);
      if(res.data.data==null){
        wx.showToast({
          title: '补签失败,只能在15天内补签',
          icon:"none"
        })
      }else{
       
        wx.showToast({
          title: '补签成功',
        })

        that.setData({
          display: "none"
        })
        that.signDetail();
        that.findSignMsg();
        that.fillDate(postDate);
        that.signContinueDays();
      }
     
    },
    fail: function (res) { 
      wx.showToast({
        title: '补签失败',
        icon: "none"
      })
    },
    complete: function (res) { },
  })


    // console.log(`点击的日期:${this.data.cur_year}年${this.data.cur_month}月${cur_day + 1}日`);
  },

  setNowDate: function () {
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const todayIndex = date.getDate();
    console.log(`日期：${todayIndex}`)
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    this.calculateEmptyGrids(cur_year, cur_month);
    this.calculateDays(cur_year, cur_month);
    this.setData({
      cur_year: cur_year,
      cur_month: cur_month,
      weeks_ch,
      todayIndex,
    })
  },

  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },
  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },
  calculateDays(year, month) {
    let days = [];
    let weekday;
    const thisMonthDays = this.getThisMonthDays(year, month);
    
    
    for (let i = 1; i <= thisMonthDays; i++) {
      var n = "";
      if (i < 10) {
        n = "0" + i
      } else {
        n = i
      }
      var myDate = new Date;
      // console.log(myDate)
      // var year = myDate.getFullYear();
      // var month = myDate.getMonth() + 1;
      var monthes="";
      if (month<10){
        monthes="0"+month 
      }else{
        monthes=month
      }
      var postDate=year+"-"+monthes;
     
      weekday = "days[" + (i - 1) + "].item"
      var day = "days[" + (i - 1) + "].day";
      this.setData({
        [weekday]: i,
        [day]: year + "-" + monthes + "-" + n,
        // src: ''
      })
     
    }

    this.fillDate(postDate);
    console.log(this.data.days)
  },
  handleCalendar(e) {
    const handle = e.currentTarget.dataset.handle;
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
 

    this.setData({
      days: []
    })

    
    if (handle === 'prev') {
      let newMonth = cur_month - 1;
      let newYear = cur_year;
      if (newMonth < 1) {
        newYear = cur_year - 1;
        newMonth = 12;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);

      let firstDay = new Date(newYear, newMonth - 1, 1);
      this.data.firstDay = firstDay.getDay();
      this.setData({
        cur_year: newYear,
        cur_month: newMonth,
        marLet: this.data.firstDay
      })
      if (this.data.month == newMonth) {
        this.setData({
          judge: 1
        })
      } else {
        this.setData({
          judge: 0
        })
      }
    } else {
      let newMonth = cur_month + 1;
      let newYear = cur_year;
      if (newMonth > 12) {
        newYear = cur_year + 1;
        newMonth = 1;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);
      let firstDay = new Date(newYear, newMonth - 1, 1);
      this.data.firstDay = firstDay.getDay();
      this.setData({
        cur_year: newYear,
        cur_month: newMonth,
        marLet: this.data.firstDay
      })
      if (this.data.month == newMonth) {
        this.setData({
          judge: 1
        })
      } else {
        this.setData({
          judge: 0
        })
      }
    }
  },
  dataTime: function () {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth();
    var months = date.getMonth() + 1;

    //获取现今年份
    this.data.year = year;

    //获取现今月份
    this.data.month = months;

    //获取今日日期
    this.data.getDate = date.getDate();

    //最后一天是几号
    var d = new Date(year, months, 0);
    this.data.lastDay = d.getDate();

    //第一天星期几
    let firstDay = new Date(year, month, 1);
    this.data.firstDay = firstDay.getDay();
  },

})